package cn.kgc.novel.controller;

import cn.kgc.novel.common.ErrorCodeEnum;
import cn.kgc.novel.common.Result;
import cn.kgc.novel.pojo.Bookcontext;
import cn.kgc.novel.pojo.Books;
import cn.kgc.novel.pojo.Bookshelf;
import cn.kgc.novel.service.BookcontextService;
import cn.kgc.novel.service.BooksService;
import cn.kgc.novel.service.UsersService;
import cn.kgc.novel.utils.SendEmail;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

//杨将
@RestController
@CrossOrigin
public class BooksController {
    @Resource
    private SendEmail sendEmail;
    @Resource
    private UsersService usersService;
    @Resource
    private BooksService booksService;
    @Resource
    private BookcontextService bookcontextService;
    //根据角色id来查找所写的小说
    @GetMapping("/findshow")
    public Result findshow(String authorid, @RequestParam(defaultValue = "1") Integer pageNum
            , @RequestParam(defaultValue = "5") Integer pageSize){
        PageHelper.startPage(pageNum, pageSize);
        List<Books> findshow = booksService.findshow(authorid);
        PageInfo<Books> findshows = new PageInfo<Books>(findshow);
        return Result.ok(findshows);
    }

    //排行榜更据性别和类型
    @GetMapping(value = "/thecharts")
    public Result thecharts( String category,@RequestParam(defaultValue = "男频") String sex,Integer pageSize,Integer pageNum){
        PageHelper.startPage(pageNum,pageSize);
        List<Books> the = booksService.thecharts(category, sex);
        PageInfo<Books> pageInfo = new PageInfo<>(the);
        return Result.ok(pageInfo);
    }
    //模糊查更据小说名字查
    @GetMapping(value = "/vaguevague")
    public Result vaguevague(String bookname,String typesof,Integer pageNum,Integer pageSize){
        List<Books> srtoeages=new ArrayList<Books>();
        List<Books> vaguevagues = booksService.vaguevague(bookname,typesof);
        System.out.println("pageNum:"+pageNum+"pageSize"+pageSize);
        PageHelper.startPage(pageNum,pageSize);
        for (Books bos:vaguevagues) {
            Books updatetime = booksService.updatetime(bos.getBookname(),typesof);
            srtoeages.add(updatetime);
        }
//        Map<String,Object> map=new HashMap<>();
//        map.put("vaguevagues",vaguevagues);
//        map.put("srtoeages",srtoeages);
        List<List<Books>> bookslist = new ArrayList<>();
        bookslist.add(vaguevagues);
        bookslist.add(srtoeages);
        PageInfo<List<Books>> pageInfo = new PageInfo<List<Books>>(bookslist);
        return Result.ok(pageInfo);
    }
    //模糊查根据更新时间字数状态来查询
    @GetMapping(value = "/vagueshow")
    public Result vagueshow(String booknames,String renewaltime,String booknum,String status,Integer pageNum,Integer pageSize){
        System.out.println("booknames:"+booknames);
        if (renewaltime.equals("全部")){
            renewaltime="";
        }
        if (status.equals("全部")){
            status="";
        }
        if (booknum.equals("30万以下")){
            booknum="20";
        }else if (booknum.equals("30-50万")){
            booknum="40";
        }else if(booknum.equals("50-100万")){
            booknum="70";
        }else if (booknum.equals("100-200万")){
            booknum="150";
        }else if (booknum.equals("200万以上")){
            booknum="210";
        }else {
            booknum="";
        }
        List<Books> vagueshow = booksService.vagueshow(booknames, renewaltime, booknum, status);
        List<Books> vagueshows= new ArrayList<Books>();
        PageHelper.startPage(pageNum,pageSize);
        for (Books va:vagueshow) {
            Books books= booksService.updatetime(va.getBookname(),null);
            vagueshows.add(books);
        }
        List<List<Books>> booklist = new ArrayList<>();
        booklist.add(vagueshow);
        booklist.add(vagueshows);
        PageInfo<List<Books>> pageInfo = new PageInfo<>(booklist);

        return Result.ok(pageInfo);
    }
    //通过uid来查看书架的书籍
    @GetMapping(value = "/findShelfById")
    public Result findShelfById(int uid,String status){
        List<Bookshelf> bookshelves=usersService.findShelfById(uid);
        if (bookshelves.size()>0){
            List<Books> booksList=booksService.getShelf(bookshelves,status);
            return Result.ok(booksList);
        }
        return Result.ok();
    }

    //查找读到的历史章节，武龙
    @GetMapping("/findhistorytitle")
    public Result findhistorytitle(int uid,String bides){
        String[] bids = bides.split(",");
        for (int i = 0; i < bids.length; i++) {
            System.out.println("bid="+bids[i]);
        }
        List<Bookshelf> bookshelves=usersService.findShelfById(uid);
        int[] titleids = new int[bids.length];
        int i = 0;
        for (String bid : bids) {
            int titleid = usersService.getHistById(uid, Integer.parseInt(bid));
            System.out.println("titleid=============="+titleid);
            for (int j = 0; j < bids.length; j++) {
                if(bids[j].equals(bid)){
                    titleids[j]=titleid;
                }
            }
        }
        for (int j = 0; j < titleids.length; j++) {
            System.out.println("titleid="+titleids[j]);
        }
        List<Bookcontext> bookcontextList = booksService.findtitles(titleids,bids);
        return Result.ok(bookcontextList);
    }

    private Books bookes = null;
    private String urlString = null;
    public Result addBooks(){
        System.out.println("private类型：urlString:"+urlString);
        System.out.println("传过来的books存储的内容："+bookes);
        try {
                Books boos=bookes;
                boos.setAvatar(urlString);
                booksService.addBooks(boos);
            return Result.ok("成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCodeEnum.OPERATION_FAILED);
        }
    }
    //查询这个作者未发布的小说 更据作者的id
    @GetMapping("/unpublished")
    public Result unpublished(Integer authorid){
        List<Books> unpublished = booksService.unpublished(authorid);
        return Result.ok(unpublished);
    }
    @PostMapping("/getBooks")
    public Books getBooks(@RequestBody Books books){
        System.out.println("getBooks中的books："+books);
        bookes=books;
        return bookes;
    }
    @PostMapping("/getimageurl")
    public String testfile(@RequestParam(value = "file") MultipartFile file){
        System.out.println(file.getOriginalFilename());
        try {
            if(!file.isEmpty()){
                //获取URL过期时间
                Date expiration = new Date(new Date().getTime() + 3600 * 1000);
                OSS ossClient = new OSSClientBuilder().build("oss-cn-beijing.aliyuncs.com", "LTAI5tASx2stzLAfVkbPNv5d", "NrCXTiKhoMtBsQf760rcZ5mEpN0Thk");
                String filename = "novel" + "/" + file.getOriginalFilename();
                System.out.println(filename);
                InputStream inputStream = file.getInputStream();
                PutObjectResult wulong01 = ossClient.putObject("wulong01", filename, inputStream);
                URL url = ossClient.generatePresignedUrl("wulong01", filename, expiration);
                String urlStringdev = url.toString();
                int i = urlStringdev.indexOf("?");
                urlString = urlStringdev.substring(0,i);
                ossClient.shutdown();

                return urlString;
            }else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }finally {
            this.addBooks();
        }

    }


    //新加
    //查询子数和人气的2个总合
    @GetMapping("/popularity")
    public Result popularity(Integer authorid){
        Map<String,Object> map=new HashMap<>();
        List<Books> popularity = booksService.popularity(authorid);
        Integer arr1=null;
        Integer arr2 = 0;
        Double arr3 = 0.0;
        Double arr4=0.0;
        for (Books bos:popularity) {
            arr1=bos.getBooknum();
            arr2=arr2+arr1;
            arr3=Double.parseDouble(bos.getPopularity());
            System.out.println(arr3);
            arr4=arr4+arr3;
        }
        map.put("arr4",arr4);
        map.put("arr2",arr2);
        return Result.ok(map);
    }

    //完结和发布小说
    @GetMapping("/wanjie")
    public Result wanjie(Integer bid,Integer uid,String status){
        System.out.println("status:"+status);
        int result = booksService.wanjie(bid,uid,status);
        return Result.ok();
    }

    //通过作者或小说名称来查找小说
    @GetMapping(value = "selectBooks")
    public Result selectBooks(@RequestParam(defaultValue = "1")Integer pageNum,
                              @RequestParam(defaultValue = "5")Integer pageSize,
                              String author,String bookname){
        PageHelper.startPage(pageNum, pageSize);
        System.out.println(author);
        List<Books> booksList = booksService.selectBooks(author,bookname);
        PageInfo<Books> pageInfo = new PageInfo<Books>(booksList);
        return Result.ok(pageInfo);
    }
    //下架书籍
    //下架书籍 2023-11-22修改
    @PostMapping(value="/deleteBook")
    public Result deleteBook( Integer bid,@RequestBody List<String> checkboxGroup1){
        Books book = this.findUsersByBid(bid);
        //封禁理由
        String notice = "";
        for (String group:checkboxGroup1) {
            notice = notice+","+ group;
        }
        String email = book.getUsers().getEmail();
        String subject = "锦途小说网";
        String text = "您的"+book.getBookname()+"由于涉嫌"+notice+"的原因已被下架";
        sendEmail.sendSimpleEmail(email,subject,text);
        booksService.deleteBook(bid);
        return Result.ok();
    }
    //2023-11-22 通过书籍id查找书籍信息和作者信xi
    private Books findUsersByBid(Integer bid){
        Books books = booksService.findUsersByBid(bid);
        return books;
    }
    //2023-11-22 通过类型id查找给类型的所有小说
    //该方法现用于删除类型时查找该类型是否有小说
    @GetMapping(value = "/findBookByTypeId")
    public Result findBookByTypeId(Integer typeid){
        List<Books> booksList = booksService.findBookByTypeId(typeid);
        return Result.ok(booksList);
    }


    @PostMapping("/deletenovel")
    public Result deletenovel(int authorid,String bookname){
        try {
            Integer selectid = booksService.selectid(bookname);
            bookcontextService.deleteBookcontext(authorid,selectid);
            booksService.deletenovel(authorid,bookname);
            return Result.ok("成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(ErrorCodeEnum.OPERATION_FAILED);
        }
    }


    //智能检索
    @GetMapping("/zhinengfind")
    public Result zhinengfind(@RequestParam("bookname") String bookname){
        System.out.println(bookname);
        List<String> zhinengbooks =  booksService.zhinengfind(bookname);
//        Iterator<String> iterator = zhinengbooks.iterator();
//        while (iterator.hasNext()){
//            String value = iterator.next();
//            zhinengbooks.add(value);
//        }
        return Result.ok(zhinengbooks);
    }


}
